package com.tianji.learning.mq;

import com.tianji.common.utils.ObjectUtils;

import com.tianji.learning.domain.dto.LikedTimesDTO;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.service.IInteractionReplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.QA_LIKED_TIMES_KEY;
import static com.tianji.common.constants.MqConstants.Queue.QA_LIKE_TIMES_QUEUE;

/**
 * 点赞消息监听器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LikeListener {
    private final IInteractionReplyService replyService;

    //1.声明消息队列
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = QA_LIKE_TIMES_QUEUE, durable = "true"),
            exchange = @Exchange(name = LIKE_RECORD_EXCHANGE, type = "topic"),
            key = QA_LIKED_TIMES_KEY
    ))
    public void updateLikeTimes(List<LikedTimesDTO> likedTimesDTOs) {
        log.info("收到点赞消息，回复id为{}", likedTimesDTOs);
        if(ObjectUtils.isEmpty(likedTimesDTOs)){
            log.error("点赞消息，异常消息，信息为空");
            return;
        }

        //批量更新回复表
        ArrayList<InteractionReply> list = new ArrayList<>(likedTimesDTOs.size());
        for (LikedTimesDTO likedTimesDTO : likedTimesDTOs) {
            InteractionReply interactionReply = new InteractionReply();
            interactionReply.setId(likedTimesDTO.getBizId());
            interactionReply.setLikedTimes(likedTimesDTO.getLikedTimes());
            list.add(interactionReply);
        }
        //更新数据库
        replyService.updateBatchById(list,100);
    }
}
